package com.xzq.codec;

import com.xzq.constans.ProtocolSupport;
import com.xzq.message.Message;
import com.xzq.serializer.Serializer;
import com.xzq.serializer.SerializerUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;

import java.util.List;

/**
 * @Author xzq
 * @Description //TODO
 * @Date 2021/11/22 20:53
 * @Version 1.0.0
 **/
public class MessageCodec extends ByteToMessageCodec {
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object o, ByteBuf byteBuf) throws Exception {
        if (o instanceof Message) {
            Message m = (Message) o;
            byteBuf.writeInt(ProtocolSupport.magicNum);
            byteBuf.writeByte(ProtocolSupport.defaultVersion);
            byteBuf.writeByte(ProtocolSupport.defaultSerializer);
            byteBuf.writeByte(m.getMessageType());
            byte[] datas = SerializerUtil.match(ProtocolSupport.defaultSerializer).serializer(m);
            byteBuf.writeInt(datas.length);
            byteBuf.writeBytes(datas);
        }
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List list) throws Exception {
        //魔数
        int magicNum = byteBuf.readInt();
        //版本号
        byte version = byteBuf.readByte();
        //序列化
        byte serialize = byteBuf.readByte();
        Serializer serializer = SerializerUtil.match(serialize);
        //消息指令
        byte messageType = byteBuf.readByte();
        Class<? extends Message> messageClass = Message.match(messageType);
        //检查协议是否支持
        if (!ProtocolSupport.isSupport(magicNum, version, serializer, messageClass)) {
            //关闭连接
            ctx.close();
            return;
        }
        int length = byteBuf.readInt();
        byte[] data = new byte[length];
        byteBuf.readBytes(data);
        Message message = serializer.derializer(data, messageClass);
        list.add(message);
    }
}
